import dashboardPageStore from "../store/DashboardPageStore";
import Exceljs from "exceljs";

export function saveTo(blob: Blob, name: string) {
    const aElement = document.createElement("a");
    aElement.setAttribute("download", name);
    const href = URL.createObjectURL(blob);
    aElement.href = href;
    aElement.setAttribute("target", "_blank");
    aElement.click();
    URL.revokeObjectURL(href);
}

export async function saveWorkbookTo(workbook: Exceljs.Workbook, name?: string) {
    let data = await workbook.xlsx.writeBuffer();
    let blob = new Blob([data], {type: ""});
    let filename = name ?? "导出数据";

    function wrapName(filename: string) {
        if (filename) {
            if (!/\.\w+$/g.test(filename)) {
                return filename + ".xlsx"
            }
        }
        return filename
    }

    saveTo(blob, wrapName(filename))
}